package com.hzjh.base.web.util

import android.content.Context
import android.content.MutableContextWrapper
import com.blankj.utilcode.util.ProcessUtils
import com.hzjh.base.web.core.JHWebView

class JHWebViewPool private constructor() {

    companion object {

        private const val TAG = "JHWebViewPool"

        @Volatile
        private var instance: JHWebViewPool? = null

        fun getInstance(): JHWebViewPool {
            return instance ?: synchronized(this) {
                instance ?: JHWebViewPool().also { instance = it }
            }
        }
    }

    private val sPool = ArrayList<JHWebView>() //List实现先进先出队列 不使用Stack
    private val lock = byteArrayOf()
    private var maxSize = 1

    /**
     * 设置 webview 池容量
     */
    fun setMaxPoolSize(size: Int) {
        synchronized(lock) { maxSize = size }
    }

    /**
     * 初始化webview 放在list中
     */
    fun init(context: Context, initSize: Int = maxSize) {
        for (i in 0 until initSize) {
            val view = JHWebView(MutableContextWrapper(context))
            sPool.add(view)
        }
    }

    /**
     * 获取webview
     */
    fun getWebView(context: Context,loadUrl:String?): JHWebView {
        WebLog.d(TAG, "getWebView() 当前进程：${ProcessUtils.getCurrentProcessName()}")
        synchronized(lock) {
            val cacheWebView=loadUrl?.let{WebCacheUtil.getPreWebView(it)}
            var webView: JHWebView =when{
                cacheWebView!=null->{
                    WebLog.d(TAG, "getWebView from cachePool")
                    cacheWebView.setCacheWeb(true)
                    cacheWebView
                }
                sPool.size > 0->{
                    WebLog.d(TAG, "getWebView from pool")
                    sPool.removeFirst()
                }
                else -> {
                    WebLog.d(TAG, "getWebView from create")
                    JHWebView(MutableContextWrapper(context))
                }
            }
            val contextWrapper = webView.context as MutableContextWrapper
            contextWrapper.baseContext = context
            WebLog.d(TAG, "getWebView hashCode --- ${webView.hashCode()}")
            return webView
        }
    }

    /**
     * 获取预加载的webview 缓存池至少留一个给后面用户使用
     */
    fun getPreWebView(context: Context): JHWebView {
        synchronized(lock) {
            val webView: JHWebView
            if (sPool.size > 1) { //防止没有命中webview cache 保留一个webview缓存池可用
                webView = sPool.removeFirst()
                webView.onResume() //缓存中获取webview没有lifecycle 手动resume
                WebLog.d(TAG, "getWebView from pool")
            } else {
                webView = JHWebView(MutableContextWrapper(context))
                WebLog.d(TAG, "getWebView from create")
            }
            val contextWrapper = webView.context as MutableContextWrapper
            contextWrapper.baseContext = context.applicationContext //预加载的webview使用application 防止内存泄漏 真正使用时会替换成对应的context进行回收
            WebLog.d(TAG, "getPreWebView hashCode --- ${webView.hashCode()}")
            return webView
        }
    }

    /**
     * 回收 WebView
     */
    fun recycle(webView: JHWebView) {
        WebLog.d(TAG,"WebView recycle")
        // 根据池容量判断是否销毁 【也可以增加其他条件 如手机低内存等等】
        val contextWrapper = webView.context as MutableContextWrapper
        contextWrapper.baseContext = webView.context.applicationContext
        synchronized(lock) {
            if (sPool.size < maxSize) {
                sPool.add(webView)
            } else {
                webView.destroy(true)
            }
        }
    }
}